<?php
// +----------------------------------------------------------------------
// | sfadmin - Suifeng Administration
// +----------------------------------------------------------------------
// | Copyright (c) 2017-2020 http://suifeng.tech All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: suifeng <1787585212@qq.com>
// +----------------------------------------------------------------------

namespace app\admin\service;

use suifeng\mvc\ServiceException;

class Access extends \suifeng\mvc\Service
{
    /**
     * 检查用户登录信息是否正确。
     */
    public function check_login($username, $password)
    {
        $username = trim($username);

        // 匹配登录方式
        if (preg_match("/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/", $username)) {
            $map['email'] = array('eq', $username); // 邮箱登陆
        } elseif (preg_match("/^1\d{10}$/", $username)) {
            $map['mobile'] = array('eq', $username); // 手机号登陆
        } else {
            $map['username'] = array('eq', $username); // 用户名登陆
        }

        $map['status'] = array('eq', 1);
        $user_info = model('admin/user')->where($map)->find();
        if (!$user_info) {
            throw new ServiceException('用户不存在或被禁用！');
        } else {
            if ($user_info['password'] && $this->md5_crypt($password) != $user_info['password']) {
                throw new ServiceException('密码错误！');
            } else {
                return $user_info;
            }
        }
    }

    /**
     * 设置登录状态。
     */
    public function auto_login($user)
    {
        // 记录登录SESSION和COOKIES
        $auth = array(
            'uid'      => $user['id'],
            'username' => $user['username'],
            'nickname' => $user['nickname'],
            'avatar'   => $user['avatar'],
        );
        session('user_auth', $auth);
        session('user_auth_sign', $this->data_sign($auth));
        return $this->is_login();
    }

    /**
     * 检测用户是否登录。
     *
     * @return integer 0-未登录，大于0-当前登录用户ID
     */
    public function is_login()
    {
        $user = session('user_auth');
        if (empty($user)) {
            return 0;
        } else {
            if (session('user_auth_sign') == $this->data_sign($user)) {
                return $user['uid'];
            } else {
                return 0;
            }
        }
    }

    /**
     * 密码加密。
     */
    public function md5_crypt($str, $auth_key = '')
    {
        if (!$auth_key) {
            $auth_key = config('AUTH_KEY') ?: 'sfadmin';
        }
        return '' === $str ? '' : md5(sha1($str) . $auth_key);
    }

    /**
     * 数据签名。
     */
    public function data_sign($data)
    {
        if (!is_array($data)) {
            $data = (array) $data;
        }
        ksort($data); //排序
        $code = http_build_query($data); // url编码并生成query字符串
        $sign = sha1($code); // 生成签名
        return $sign;
    }

    public function is_super_user()
    {
        $user = session('user_auth');
        if (!empty($user['group_id'])) {
            if ($user['group_id'] == ADMIN_SUPER_GROUP_ID) {
                return true;
            }
        }
        return false;
    }

    /**
     * 检查是否有角色?
     *
     * @param unknown $group_id
     * @param unknown $role_name
     * @return boolean
     */
    public function has_role($role_name)
    {
        if ($this->is_super_user()) {
            return true;
        }

        $auth_info = session('user_auth');
        $group_info = model('admin/group')->get_group_info($auth_info['group_id']);
        if (!empty($group_info['admin_roles'])) {
            return in_array($role_name, $group_info['admin_roles']);
        }

        return false;
    }

    /**
     * 检查是否有权限?
     *
     * @param unknown $permission_name
     * @return boolean
     */
    public function has_permission($permission_name)
    {
        if ($this->is_super_user()) {
            return true;
        }

        $auth_info = session('user_auth');
        $group_info = model('admin/group')->get_group_info($auth_info['group_id']);
        if (!empty($group_info['admin_auth'])) {
            return in_array($permission_name, $group_info['admin_auth']);
        }

        return false;
    }

}
